<template>
  <div class="add-move-storage">
    <el-card>
      <div class="form-header">
        <div class="form-title">编辑调拨单</div>
        <div class="required-tip">*为必填项</div>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="调拨单号">
              <el-input
                v-model="form.movingCode"
                placeholder="可不填写,自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调拨单类型" prop="allotWarehouseType">
              <el-select
                v-model="form.allotWarehouseType"
                placeholder="请选择调拨类型"
              >
              <el-option label="调拨上架" value="调拨上架" />
                <el-option label="仓库调拨" value="仓库调拨" />
                <el-option label="报损调拨" value="报损调拨" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input v-model="form.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input :value="form.creatorName" readonly disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="form.createTime"
                type="date"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="2"
                maxlength="300"
                show-word-limit
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span class="form-title">产品信息</span>
          <el-button type="primary" @click="fetchProductOptions"
            >+ 新增产品</el-button
          >
        </div>
      </template>
      <el-table :data="productList" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="allotCount" label="数量">
          <template #default="scope">
            <el-input v-model="scope.row.allotCount" placeholder="输入数量" />
          </template>
        </el-table-column>
        <el-table-column prop="currentLocation" label="当前库位">
          <template #default="scope">
            <span>{{ scope.row.currentLocation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调拨库位" width="300">
          <template #default="scope">
            <div style="display: flex; gap: 8px">
              <el-select
                v-model="scope.row.original_Position"
                placeholder="选择仓库"
                style="width: 120px"
                @change="(value: number) => handleWarehouseChange(value, scope.$index)"
              >
                <el-option
                  v-for="warehouse in warehouseOptions"
                  :key="warehouse.id"
                  :label="warehouse.warehouse_Name"
                  :value="warehouse.id"
                />
              </el-select>
              <el-select
                v-model="scope.row.new_StorageId"
                placeholder="选择库位"
                style="width: 120px"
                :disabled="!scope.row.original_Position"
              >
                <el-option
                  v-for="storage in scope.row.storageOptions"
                  :key="storage.id"
                  :label="storage.storage_Name"
                  :value="storage.id"
                />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
              type="text"
              @click="removeProduct(scope.$index, scope.row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="80%">
      <!-- 查询区域 -->
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="searchForm.product_Number"
          placeholder="请输入编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="searchForm.product_Name"
          placeholder="请输入名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchProductOptions">搜索</el-button>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="storage_Unit" label="存储单位" />
        <el-table-column prop="packaging_Type" label="包装类型" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="weight" label="重量" />
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery1.totalCount"
            >
              共{{ pageQuery1.totalCount }}条 每页显示{{
                pageQuery1.pagesize
              }}条 当前第{{ pageQuery1.pageindex }}页/共{{
                pageQuery1.totalPage
              }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery1.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery1.pageindex == 1"
                @click="pageQuery1.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery1.totalCount"
            >
              <el-button
                :disabled="pageQuery1.pageindex == pageQuery1.totalPage"
                @click="pageQuery1.pageindex = pageQuery1.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showProductDialog = false">关闭</el-button>
        <el-button type="primary" @click="onSelectProducts">选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Delete } from "@element-plus/icons-vue";

import type { ComponentSize } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
const size = ref<ComponentSize>("default");
import axios from "axios";
import { StorageRed, StorageWrite } from "@/http/axiosHelper";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { statementRed } from "@/http/axiosHelper";
import { statementWrite } from "@/http/axiosHelper";

const router = useRouter();
const route = useRoute();
const form: any = reactive({
  tableType: 0,
  movingCode: "",
  allotWarehouseType: "",
  allotCount: 0,
  orderCode: "",
  original_Warehouse: "",
  original_StorageId: "",
  original_Position: "",
  new_StorageId: "",
  reviewer: "",
  reason: "",
  notes: "",
  state: "",
  batch: "",
  createUse: "", // 用户ID（数字）
  creatorName: "", // 用户姓名（显示用）
  createTime: "",
});

interface ProductItem {
  id: Number;
  product_Id: Number;
  product_Number: string;
  product_Name: string;
  specifications: string;
  category_ID: Number;
  category_Name: string;
  batch: string;
  storage_Unit: string;
  packaging_Type: string;
  price: string;
  weight: Number;
  allotCount: Number;
  warehouse_Name: string;
  storage_Name: string;
  storageOptions?: any[];
  original_Position: Number;
  new_StorageId: Number;
  warehouse_ID: Number;
  storage_ID: Number;
}

const productList: any = ref<ProductItem[]>([]);

// 仓库选项
const warehouseOptions = ref<any[]>([]);

// 获取仓库列表
function fetchWarehouseOptions() {
  return StorageRed({
    url: "/api/Warehouse_InOrOut/GetWarehouseModel",
    method: "get",
  }).then((res) => {
    if (res.data.code === 200) {
      warehouseOptions.value = res.data.data || [];
    }
    return res;
  });
}

// 根据仓库ID获取库位列表
function fetchStorageOptions(warehouseId: number, rowIndex: number) {
  return StorageRed({
    url: "/api/Warehouse_InOrOut/GetStorageModel",
    method: "get",
    params: {
      warehouse_ID: warehouseId,
    },
  }).then((res) => {
    if (res.data.code === 200) {
      productList.value[rowIndex].storageOptions = res.data.data || [];
    }
    return res;
  });
}

// 处理仓库选择变化
function handleWarehouseChange(warehouseId: number, rowIndex: number) {
  // 清空库位选择
  productList.value[rowIndex].new_StorageId = null;
  productList.value[rowIndex].storageOptions = [];

  if (warehouseId) {
    fetchStorageOptions(warehouseId, rowIndex);
  }
}


// 控制弹窗显示
const showProductDialog = ref(false);

// 查询商品表单
const searchForm = ref({
  product_Number: "",
  product_Name: "",
});

// 商品数据（实际应从接口获取）
const productOptions = ref([]);

// 获取商品列表
function fetchProductOptions() {
  showProductDialog.value = true;
  StorageRed({
    url: "/api/Reporting_losses/GetProductByWarehouse_InOrOut",
    method: "get",
    params: {
      product_Number: searchForm.value.product_Number,
      product_Name: searchForm.value.product_Name,
      pageindex: pageQuery1.pageindex,
      pagesize: pageQuery1.pagesize,
    },
  }).then((res) => {
    productOptions.value = res.data.data;
    pageQuery1.totalCount = res.data.totalCount;
    pageQuery1.totalPage = res.data.totalPage;
  });
}

onMounted(async () => {
  await onView();
});

//编辑反填
async function onView() {
  try {
    const res = await StorageRed({
      url: "/api/AllotMoving_Inventory/GetAllotMoving_InventoryDetail",
      method: "get",
      params: {
        batch: route.query.batch,
        tableType: 2,
      },
    });

    console.log("编辑反填数据:", res.data.data);
    if (res.data && res.data.data) {
      // 如果返回的是数组，取第一个作为主表信息
      if (Array.isArray(res.data.data)) {
        console.log("编辑反填数据:", res.data.data);
        // 处理产品列表数据，确保字段映射正确
        productList.value = res.data.data.map((item: any) => ({
          id: item.id,
          warehouse_InOrOutId: item.warehouse_InOrOutId,
          productCode: item.product_Number,
          productName: item.product_Name,
          specifications: item.specifications,
          price: Number(item.price) || 0,
          product_Id: item.product_Id,
          category_Name: item.category_Name,
          batch: item.batch,
          allotCount: item.allotCount,
          currentLocation:
            item.original_WarehouseName + ":" + item.original_StorageName,
          original_Position: item.original_Position,
          new_StorageId: item.new_StorageId,
          storageOptions: [], // 初始化库位选项
          original_Warehouse: item.original_Warehouse,
          original_StorageId: item.original_StorageId,
        }));

        // 设置表单数据
        Object.assign(form, res.data.data[0]);

        // 保存原有批次号，用于后续添加产品时统一批次
        if (res.data.data[0]?.batch) {
          form.existingBatch = res.data.data[0].batch;
        }

        // 加载仓库选项
        await fetchWarehouseOptions();

        // 为每个产品项加载对应的库位选项
        for (let i = 0; i < productList.value.length; i++) {
          const item = productList.value[i];
          if (item.original_Position) {
            await fetchStorageOptions(item.original_Position, i);
          }
        }
      } else {
        // 如果返回的是对象，直接使用
        productList.value = res.data.data;
        form.value = [res.data.data];

        // 设置表单数据（对象情况）
        form.movingCode = res.data.data?.movingCode || "";
        form.warehouse_InOrOutId = res.data.data?.warehouse_InOrOutId || "";
        form.allotWarehouseType = res.data.data?.allotWarehouseType || "";
        form.orderCode = res.data.data?.orderCode || "";
        form.notes = res.data.data?.notes || "";
        form.creatorName = res.data.data?.creatorName || "";
        form.createTime = res.data.data?.createTime || "";
        form.original_Warehouse = res.data.data[0]?.original_Warehouse || "";
        form.original_StorageId = res.data.data[0]?.original_StorageId || "";
        form.original_Position = res.data.data[0]?.original_Position || "";
        form.new_StorageId = res.data.data[0]?.new_StorageId || "";

        // 保存原有批次号
        if (res.data.data?.batch) {
          form.existingBatch = res.data.data.batch;
        }
      }
    } else {
      // 如果没有数据，清空显示
      productList.value = [];
      form.movingCode = "";
      form.allotWarehouseType = "";
      form.orderCode = "";
      form.notes = "";
      form.creatorName = "";
      form.createTime = "";
      form.original_Warehouse = "";
      form.original_StorageId = "";
      form.original_Position = "";
      form.new_StorageId = "";
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  }
}

// 选中的商品
const selectedProducts = ref<ProductItem[]>([]);

// 修改 handleSelectionChange，确保深拷贝
function handleSelectionChange(val: ProductItem[]) {
  selectedProducts.value = val.map((item) => ({ ...item })); // 深拷贝
}

// 批量添加到移库产品表格
function onSelectProducts() {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning("请先选择要添加的产品");
    return;
  }

  

  // 确定批次号：如果有现有批次则使用现有批次，否则生成新批次
  let batchCode = "";
  if (form.existingBatch) {
    // 如果有现有批次，使用现有批次
    batchCode = form.existingBatch;
  } else {
    // 如果没有现有批次，生成新批次
    batchCode = generateBatchCode();
    // 同时更新现有批次号，确保后续添加的产品都使用同一批次
    form.existingBatch = batchCode;
  }

  // 添加所有选中的产品到表格（不进行重复过滤）
  productList.value.push(
    ...selectedProducts.value.map((row) => {
      console.log("处理商品行数据:", row);
      return {
        id: row.id,
        productCode: row.product_Number,
        productName: row.product_Name,
        specifications: row.specifications,
        price: Number(row.price) || 0,
        product_Id: row.product_Id,
        category_Name: row.category_Name,
        newLocation: "",
        batch: batchCode, // 统一批次号
        allotCount: "",
        original_Warehouse: row.warehouse_ID,
        original_StorageId: row.storage_ID,
        currentLocation: row.warehouse_Name + ":" + row.storage_Name,
        original_Position: "",
        new_StorageId: "",
      };
    })
  );

  ElMessage.success(`成功添加${selectedProducts.value.length}个产品`);

  // 统一所有产品的批次号
  unifyBatchForAllProducts();

  // 重置状态
  showProductDialog.value = false;
  selectedProducts.value = [];
}

const pageQuery1: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});

// 删除产品行
function removeProduct(index: any, row: any) {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 如果有报损单号，调用后端删除接口
      if (row.reporting_LossesCode) {
        StorageWrite({
          url: "/api/AllotMoving_Inventory/DeleteAllotMovingById",
          method: "delete",
          params: {
            id: row.id,
          },
        }).then((res: any) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            // 从本地列表中移除
            productList.value.splice(index, 1);
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      } else {
        // 如果没有移库单号（新增的产品），直接从本地列表中移除
        productList.value.splice(index, 1);
        ElMessage.success("删除成功");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}

// 提交调拨单
function onSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error("请完善必填项！");
      return;
    }

    if (productList.value.length === 0) {
      ElMessage.error("请至少添加一个产品！");
      return;
    }

    // 确定最终批次号：优先使用现有批次，如果没有则使用第一个产品的批次
    const finalBatch =
      form.existingBatch ||
      (productList.value.length > 0 ? productList.value[0].batch : "");

    // 1. 遍历产品列表，合并表单信息
    const items = productList.value.map((row: any) => ({
      ...form, // 上部分表单信息
      // 下部分产品信息，覆盖或补充form中的同名字段
      id: row.id,
      warehouse_InOrOutId: row.warehouse_InOrOutId,
      product_Id: row.product_Id,
      product_Number: row.productCode,
      product_Name: row.productName,
      specifications: row.specifications,
      price: Number(row.price) || 0,
      batch: finalBatch, // 统一使用最终批次号
      allotCount: Number(row.allotCount) || 0,
      original_Warehouse: row.original_Warehouse,
      original_StorageId: row.original_StorageId,
      original_Position: row.original_Position,
      new_StorageId: row.new_StorageId,
      tableType: 2,
    }));
    console.log(items);
    // 2. 组装参数对象
    const params = { items };

    // 3. 调用接口
    StorageWrite({
      url: "/api/AllotMoving_Inventory/UpdateAllotMoving_Inventory",
      method: "put",
      data: params,
    }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        router.push("/TransferStorageView");
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
}

function onCancel() {
  router.back();
}

watch(pageQuery1, () => {
  fetchProductOptions();
});

//生成批次号
function generateBatchCode() {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < 5; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 统一所有产品的批次号
function unifyBatchForAllProducts() {
  if (form.existingBatch && productList.value.length > 0) {
    // 如果有现有批次，将所有产品的批次号统一为现有批次
    productList.value.forEach((product: any) => {
      product.batch = form.existingBatch;
    });
  }
}

// 表单ref
const formRef = ref<FormInstance>();

// 校验规则
const rules: FormRules = {
  allotWarehouseType: [
    { required: true, message: "调拨类型不能为空", trigger: "change" },
  ],
};
</script>

<style scoped>
.add-move-storage {
  padding: 20px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.form-title {
  font-size: 16px;
  font-weight: bold;
}

.required-tip {
  font-size: 12px;
  color: #999;
}
</style>
